﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ArivisTests.Models;

namespace ArivisTests.Controllers
{
    [Authorize]
    public class UserTestsController : Controller
    {
        private ArivisTestsDBContext db = new ArivisTestsDBContext();

        //
        // GET: /UserTests/

        public ActionResult Index()
        {
            // create view model
            var model = new UserTestsModel();
            int userId = WebMatrix.WebData.WebSecurity.CurrentUserId;

            // get the most recent test run with open tests for the current user
            model.CurrentRun = db.TestRunsWithDetails
                .Where(run => run.Active)
                .Where(run => run.Tests.Any(test => test.User != null && test.User.UserId == userId))
                .OrderByDescending(run => run.Date)
                .FirstOrDefault();

            // get test for current user
            if (model.CurrentRun != null)
            {
                model.UserTests = model.CurrentRun.Tests.Where(test => test.User != null && test.User.UserId == userId).OrderBy(test => test.Order).ToList();
            }
            else
            {
                model.UserTests = new List<TestCase>();
            }

            // get next test for current user
            model.NextTest = model.UserTests.FirstOrDefault(test => test.Result == null);

            // create view
            return View(model);
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}
